package com.core.netty.http.work;

import com.core.netty.http.Intercept.MyIntercept;
import com.core.spring.DefaultMyApplication;
import com.core.spring.IocBeanFactory;
import com.core.springmvc.MyDispatcherServlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SerlvetUtil {

    private static volatile Map<String, MySerlvet> serlvets = new HashMap<>();

    public static void put(String name, MySerlvet serlvet) {
        serlvets.put(name, serlvet);
    }

    public static MySerlvet get(String name) {
        return serlvets.get(name);
    }

    public static Map<String, MySerlvet> getMap() {
        return serlvets;
    }

    public static void init() {

        List<Class<?>> serlvetClassList = ((DefaultMyApplication) IocBeanFactory.getInstant()).getSerlvetClassList();

        for (Class<?> clazz : serlvetClassList) {
            Object o = null;
            try {
                o = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (o instanceof MyIntercept) {
                if (clazz.isAnnotationPresent(MySerlvetUrl.class)) {
                    MySerlvetUrl url = clazz.getAnnotation(MySerlvetUrl.class);
                    serlvets.put(url.value(), (MySerlvet) o);
                }
            }
        }
    }

    public static void addClass(Class<?> clazz) {
        Object o = null;
        try {
            o = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (o instanceof MySerlvet) {
            if (clazz.isAnnotationPresent(MySerlvetUrl.class)) {
                MySerlvetUrl url = clazz.getAnnotation(MySerlvetUrl.class);
                serlvets.put(url.value(), (MySerlvet) o);
            }
        }

    }

    public static void initSerlvet() {
        //添加myspringmvc
        addClass(MyDispatcherServlet.class);
        SerlvetUtil.getMap().forEach((k, v) -> {
            v.init();
        });
    }
}
